﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using SCM.Common;
using SCM.Common.Attributes;
using SCM.Common.Extensions;
using SCM.Model;
using SCM.Model.DBEntity;
using SCM.Servie.IBusiness;
using System;
using System.Linq;

namespace SCM.WebAPI.Controllers
{
    /// <summary>
    /// 认证接口
    /// </summary>
    [ApiController]
    [SCMAuthorize]
    [Route("[controller]")]
    public class AuthController : BaseController
    {
        private readonly ILogger<AuthController> _logger;

        /// <summary>
        /// 构建
        /// </summary>
        /// <param name="logger"></param>
        public AuthController(ILogger<AuthController> logger)
        {
            _logger = logger;
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public ViewDataPack<LoginResultVo> Login(LoginRequestVo model)
        {
            var userService = GetService<IUserService>();

            T_User user = null;
            if (!string.IsNullOrWhiteSpace(model.Phone))
            {
                user = userService.GetByPhone(model.Phone, EncryptHelper.HashMD5String(model.Password));
            }
            else
            {
                return new ViewDataPack<LoginResultVo> { Code = ResultCode.LoginFailed, Message = "手机号不能为空" };
            }
            if (user == null)
            {
                return new ViewDataPack<LoginResultVo> { Code = ResultCode.LoginFailed, Message = "密码错误" };
            }
            else
            {
                if (user.DataStatus == DataStatusEnum.Custom || user.DataStatus == DataStatusEnum.Disable)
                {
                    return new ViewDataPack<LoginResultVo> { Code = ResultCode.LoginFailed, Message = "当前用户已禁用,请联系沟通" };
                }
                if (user.DataStatus == DataStatusEnum.Draft || user.DataStatus == DataStatusEnum.Invalid)
                {
                    return new ViewDataPack<LoginResultVo> { Code = ResultCode.LoginFailed, Message = "当前用户未审核通过,请联系沟通" };
                }
                if (user.ValidDate <= DateTime.Now)
                {
                    return new ViewDataPack<LoginResultVo> { Code = ResultCode.LoginFailed, Message = "当前用户已过期,请联系沟通" };
                }

                var userRoleService = GetService<IUserRoleService>();
                var userRoles = userRoleService.GetList(user.CompanyID, user.ID);
                var roleIds = userRoles.Select(p => p.RoleID).ToArray();

                string token = TokenLogin(user, roleIds);
                var loginResult = new LoginResultVo() { User = user, Token = token };
                return new ViewDataPack<LoginResultVo>() { Code = ResultCode.OK, Data = loginResult };
            }
        }
    }
}
